import React, { FC, useState, useEffect } from "react";
// import "./List.css";
import QuestionCard from "../Question/QuestionCard";
import { produce } from "immer";

const List2: FC = () => {
  useEffect(() => {
    console.log("加载一个Ajax请求");
  }, []); // 数组是一个依赖,数组是空的就是无依赖

  // 列表页
  // 问卷数据
  const [questionList, setQuestionList] = useState([
    { id: "q1", title: "问题1", isPubilshed: true },
    { id: "q2", title: "问题1", isPubilshed: false },
    { id: "q3", title: "问题1", isPubilshed: true },
    { id: "q4", title: "问题1", isPubilshed: false },
  ]);

  // 添加问卷
  function add() {
    const num = Math.random().toString().slice(-3);
    // setQuestionList([
    //   ...questionList,
    //   {
    //     id: "q" + num,
    //     title: "SerMs" + num,
    //     isPubilshed: false,
    //   },
    // ]);

    setQuestionList(
      produce((darft) => {
        darft.push({
          id: "q" + num,
          title: "SerMs" + num,
          isPubilshed: false,
        });
      }),
    );
  }

  // 发布问卷
  function publishQuertion(id: string) {
    setQuestionList(
      //   questionList.map((q) => {
      //     if (q.id !== id) return q;
      //     return {
      //       ...q,
      //       isPubilshed: true,
      //     };
      //   }),
      produce((darft) => {
        const q = darft.find((item) => item.id === id);
        if (q) q.isPubilshed = true;
      }),
    );
  }

  // 删除问卷
  function delQuertion(id: string) {
    setQuestionList(
      //   questionList.filter((q) => {
      //     // 数组删除
      //     if (q.id === id) return false;
      //     return true;
      //   }),

      produce((darft) => {
        const index = darft.findIndex((q) => q.id === id);
        darft.splice(index, 1);
      }),
    );
  }
  return (
    <div>
      <h1>问卷列表2</h1>
      <div>
        {questionList.map((question) => {
          const { id, title, isPubilshed } = question;
          return (
            <QuestionCard
              key={id}
              id={id}
              title={title}
              isPublished={isPubilshed}
              delQuertion={delQuertion}
              publishQuertion={publishQuertion}
            />
          );
        })}
      </div>
      <div>
        <button onClick={add}>新增问卷</button>
      </div>
    </div>
  );
};

export default List2;
